package com.linkit.main.article;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.linkit.config.PageLinks;
import com.linkit.controller.ArticlesHandler;
import com.linkit.exception.ErrorCodes;
import com.linkit.exception.FTExceptions;
import com.linkit.main.AbstractPage;
import com.linkit.main.ControllerId;
import com.linkit.main.MainActivity;
import com.linkit.main.R;
import com.linkit.main.setting.SettingsLayout;
import com.linkit.main.widget.ExtendedButton;
import com.linkit.model.Article;
import com.linkit.model.HttpParams;
import com.linkit.model.ServiceTaskResult;
import com.linkit.utils.Constants;
import com.linkit.utils.ServiceUtils;
import com.linkit.utils.Utils;
import com.linkit.widget.loadmore.LoadMoreListView;
import com.linkit.widget.loadmore.LoadMoreListView.OnLoadMoreListener;

/**
 * Hiện thị các tin tức mới nhất
 * 
 */
public class ArticlesLayout extends AbstractPage implements
		OnItemClickListener, OnClickListener {

	public static final int INIT = 0;
	public static final int REFRESH = 1;
	public static final int PUSH_TO_LOAD = 2;

	private MainActivity main;
	private LoadMoreListView listView;
	private ArrayList<Article> list;
	private ArticlesAdapter adapter;

	public ArticlesLayout() {
		main = MainActivity.getInstance();
	}

	/**
	 * Hiện thị danh sách tin tức
	 * 
	 * @param list
	 */
	public void showPage(ArrayList<Article> list) {

		this.list = list;

		showPages();

		// ẩn dialog đợi dữ liệu từ server
		main.dialogManager.hideDialog(null);
	}

	/**
	 * Hiện thị danh sách tin tức
	 * 
	 * @param list
	 */
	public void refresh(ArrayList<Article> list) {

		this.list = list;

		Collections.sort(list);

		adapter.notifyDataSetChanged();

		listView.setSelection(0);

		// ẩn dialog đợi dữ liệu từ server
		main.dialogManager.hideDialog(null);
	}

	/**
	 * Hiện thị thêm danh sách trong listview
	 * 
	 * @param list
	 */
	public void loadItem(ArrayList<Article> list) {

		this.list.addAll(list);

		Collections.sort(list);

		adapter.notifyDataSetChanged();

		// Call onLoadMoreComplete when the LoadMore task, has finished
		listView.onLoadMoreComplete();

		// ẩn dialog đợi dữ liệu từ server
		main.dialogManager.hideDialog(null);
	}

	@Override
	public void setControllerId() {
		main.setControllerId(ControllerId.ARTICLES_LAYOUT);
	}

	@Override
	public void showHeader() {
		main.setVisibleHeader(true);
		// Add header
		RelativeLayout tabLayout = (RelativeLayout) RelativeLayout.inflate(
				main, R.layout.article_header_tab, null);
		main.setConfigHeader(tabLayout, this);

		ExtendedButton topBtn = (ExtendedButton) tabLayout
				.findViewById(R.id.news_top_btn);
		topBtn.setOnClickListener(this);

		ExtendedButton f5Btn = (ExtendedButton) tabLayout
				.findViewById(R.id.news_refresh_btn);
		f5Btn.setOnClickListener(this);
	}

	@Override
	public void showContent() {
		main.setOnBackPressedImpl(this);
		// khởi tạo param
		listView = (LoadMoreListView) layout
				.findViewById(R.id.lookup_router_companys_listview);
		listView.setOnItemClickListener(this);

		Collections.sort(list);

		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			public void onLoadMore() {
				HttpParams config = getArticle(null, null, null,
						list.get(list.size() - 1).time);
				new LoadDataTask().execute(config);
			}
		});

		// cập nhật dữ liệu
		updateListView(list);

		// thêm nội dung vào danh sách tra cứu
		main.contentManager.addContentLayout(layout);

		// đặt thời gian hiện thị quảng cáo
		main.scheduleAdvertise();
	}

	@Override
	protected void setLayout() {
		// khởi tạo layout
		layout = (RelativeLayout) LinearLayout.inflate(main,
				R.layout.article_layout, null);

	}

	private void updateListView(ArrayList<Article> list) {
		adapter = new ArticlesAdapter(list);
		listView.setAdapter(adapter);
	}

	@Override
	public void onBackPressed() {

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();

		switch (id) {
		case R.id.news_top_btn:
			listView.setSelection(0);
			break;
		case R.id.news_refresh_btn:
			ArticlesHandler articlesHandler = new ArticlesHandler(this);
			articlesHandler.doRequest(REFRESH, null, null, null, null);
			break;
		case R.id.header_title_layout:
			SettingsLayout settingsLayout = new SettingsLayout(this);
			settingsLayout.init();
			break;
		}
	}

	private class LoadDataTask extends
			AsyncTask<HttpParams, Void, ServiceTaskResult<String>> {

		@Override
		protected ServiceTaskResult<String> doInBackground(HttpParams... params) {

			if (isCancelled()) {
				return null;
			}
			ServiceTaskResult<String> result = new ServiceTaskResult<String>();
			String data = "";
			try {
				data = ServiceUtils.getServiceByGet(params[0]);
				result.setResult(data);
			} catch (Exception e) {
				result.setException(e);
			}

			return result;
		}

		@Override
		protected void onPostExecute(ServiceTaskResult<String> result) {

			if (!result.hasException()) {

				String resultStr = (String) result.getResult();
				
				try {
					list.addAll(getNewsList(resultStr));
					adapter.notifyDataSetChanged();
				} catch (Exception e) {
//					e.printStackTrace();
				}
				
			}

			listView.onLoadMoreComplete();

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			listView.onLoadMoreComplete();
		}

		/**
		 * Lấy tin tức mới nhất
		 * 
		 * @param data
		 * @return
		 * @throws Exception
		 */
		private ArrayList<Article> getNewsList(String data) throws Exception {
			
			if (data.length() == 0) throw new FTExceptions(ErrorCodes.NO_RESULT_ERROR);

			JSONArray jsonList = new JSONArray(data);

			if (jsonList.length() == 0) throw new FTExceptions(ErrorCodes.NO_RESULT_ERROR);

			ArrayList<Article> article = Utils.getNewsList(jsonList);

			return article;
		}
	}

	/**
	 * Lấy thông tin các tuyến xe khách theo tỉnh - tỉnh
	 */
	public HttpParams getArticle(String siteId, String cats, Integer type,
			Long date) {

		HttpParams configParameters = new HttpParams();

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		if (siteId != null) {
			nameValuePairs.add(new BasicNameValuePair("", siteId));
		}

		if (cats != null) {
			nameValuePairs.add(new BasicNameValuePair("", cats));
		}

		if (type != null) {
			nameValuePairs
					.add(new BasicNameValuePair("", String.valueOf(type)));
		}

		if (date != null) {
			nameValuePairs.add(new BasicNameValuePair("lastDate", String
					.valueOf(date)));
		}

		configParameters.setUrl(Constants.WEBSERVICE_URL);
		if (!nameValuePairs.isEmpty()) {
			configParameters.setParameters(nameValuePairs);
		}

		configParameters.setMethodName(PageLinks.ACTICLES_LIST.getName());

		return configParameters;
	}
}